package com.zyj.controller;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
public class ZipDownloadController {

    @GetMapping("/download")
    public ResponseEntity<byte[]> download() throws IOException {
        // 多个字符串内容
        List<String> stringContents = new ArrayList<>();
        stringContents.add("Content of file 1.");
        stringContents.add("Content of file 2.");
        // 添加更多字符串...

        // 创建一个字节数组输出流，用于保存压缩包内容
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(baos)) {
            // 循环处理每个字符串内容并添加到压缩包
            for (int i = 0; i < stringContents.size(); i++) {
                String content = stringContents.get(i);
                String entryName = "1/2/3/file" + (i + 1) + ".txt";

                // 创建ZIP条目
                zipOutputStream.putArchiveEntry(new ZipArchiveEntry(entryName));

                // 将字符串内容写入ZIP文件
                zipOutputStream.write(content.getBytes());

                // 关闭当前ZIP条目
                zipOutputStream.closeArchiveEntry();
            }
        }

        // 设置HTTP响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", "files.zip");

        // 将压缩包内容转换为字节数组
        byte[] zipBytes = baos.toByteArray();

        // 构造ResponseEntity对象
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(zipBytes, headers, HttpStatus.OK);
        return responseEntity;
    }
}
